/*   Copyright (C) 2011 Wolfgang Hankeln, Norma J. Wendel
 *
 *   This file is part of CDinFusion.
 *
 *   CDinFusion is free software: you can redistribute it and/or
 *   modify it under the terms of the GNU Lesser General Public 
 *   License in version 3 (LGPL3) as published by the Free Software
 *   Foundation version 3 of the License.
 *
 *   CDinFusion is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 *   Lesser General Public License for more details.
 *
 *   You should have received a copy of the Lesser General Public
 *   License along with CDinFusion; see the file COPYING. If not,
 *   write to the Free Software Foundation, 59 Temple Place - Suite 330,
 *   Boston, MA 02111-1307, USA or see <http://www.gnu.org/licenses/>.
 *   
 *   If you have any questions, send an email to: megx@mpi-bremen.de.
 */
package org.cdinfusion.web.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.cdinfusion.data.CDElement;
import org.cdinfusion.data.GetInformation;
import org.cdinfusion.data.environment.Environment;
import org.cdinfusion.data.studytype.StudyType;
import org.cdinfusion.filehandling.CSVHandler;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

public class GSC_c_Controller extends AbstractController {

	public ModelAndView handleRequestInternal(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		System.out.println("##### GSC_c_Controller #####");

		HttpSession session = request.getSession();

		String origin = "";
		origin = (String) session.getAttribute("origin");
		String fromID = "";
		String toID = "";
		String branch = (String) request.getParameter("branch");
		session.setAttribute("branch", branch);

		String context_exists = (String) session.getAttribute("context_exists");
		String studytype = "";
		String envtype = "";
		String sessionID = "";
		String button = request.getParameter("submit");
		List<String> sSeqID = new ArrayList<String>();
		List<String> usedSequenceIDs = new ArrayList<String>();
		String msg = "";
		ModelAndView mav = null;
		boolean first = Boolean.parseBoolean(request.getParameter("first"));
		// TODO: Exception handling
		studytype = request.getParameter("StudyTypeDropDown");
		envtype = request.getParameter("EnvParamDropDown");
		fromID = request.getParameter("FromSeqID").trim();
		toID = request.getParameter("ToSeqID").trim();
		List<String> allSequenceIDs = (List<String>) session
				.getAttribute("allSequenceIDs");
		List<String> currentlySelectedSIDs = new ArrayList<String>();

		if (context_exists.equals("yes")) {
			String second_step = (String) session.getAttribute("second_step");
			if (second_step.equals("true")) {
				List<String> old_usedSequenceIDs = (List<String>) session
						.getAttribute("old_usedSequenceIDs");
				usedSequenceIDs = old_usedSequenceIDs;
			}
		}

		boolean add_now = false;

		for (int i = 0; i < allSequenceIDs.size(); i++) {
			if (allSequenceIDs.get(i).equals(fromID))
				add_now = true;
			if (add_now) {
				if (!button.contains("download empty csv"))
					usedSequenceIDs.add(allSequenceIDs.get(i));
				currentlySelectedSIDs.add(allSequenceIDs.get(i));
			}
			if (allSequenceIDs.get(i).equals(toID))
				add_now = false;
		}
		session.setAttribute("usedSequenceIDs", usedSequenceIDs);
		session.setAttribute("currentlySelectedSIDs", currentlySelectedSIDs);
		session.setAttribute("context_exists", "yes");
		final int numberOfSequences = ((Integer) session
				.getAttribute("numberOfSequencesUploaded")).intValue();
		
		StudyType study = null;
		Environment env = null;
		
		try {
			study = (StudyType) Class.forName("org.cdinfusion.data.studytype." + studytype.toUpperCase()).newInstance();
		} catch (final Exception e) {
			System.out.println(e);
			System.out.printf("Could not create StudyType object for %s.", studytype);
		}
		try {
			env = (Environment)Class.forName("org.cdinfusion.data.environment." + StringUtils.capitalize(envtype)).newInstance();
		} catch (final Exception e) {
			System.out.println(e);
			System.out.printf("Could not create Environment object for %s.", envtype);
		}
		
		
		final List<CDElement> cdeLIST;
		if (context_exists.equals("yes")) {
			cdeLIST = (List<CDElement>) session.getAttribute("cdeLIST");
		} else {
			cdeLIST = new ArrayList<CDElement>();
		}
		
		final CDElement cdelem = new CDElement(
				currentlySelectedSIDs.get(0),
				currentlySelectedSIDs.get(currentlySelectedSIDs.size() - 1),
				currentlySelectedSIDs.size(), study, env, null, false);
		cdeLIST.add(cdelem);
		
		session.setAttribute("cdeLIST", cdeLIST);


		if (env == null || study == null || "none".equals(studytype) || "none".equals(envtype)) {
			ModelAndView errmav = new ModelAndView("ErrorPage");
			errmav.addObject("origin", origin);
			return errmav;
		}

		sessionID = request.getSession().getId();
		button = request.getParameter("submit");
		boolean stop = false;
		if (!fromID.equals(toID)) {
			for (int i = 0; i < allSequenceIDs.size(); i++) {
				if (allSequenceIDs.get(i).equals(fromID)) {
					for (int j = i; j < allSequenceIDs.size(); j++) {
						sSeqID.add(allSequenceIDs.get(j).trim());
						if (allSequenceIDs.get(j).equals(toID)) {
							stop = true;
							break;
						}
					}// end for j
				}// end if
				if (stop == true) {
					break;
				}
			}// end for i
		}
		if (fromID.equals(toID)) {
			for (int i = 0; i < allSequenceIDs.size(); i++) {
				if (allSequenceIDs.get(i).equals(fromID)) {
					sSeqID.add(allSequenceIDs.get(i).trim());
				}
			}
		}// end if(fromID.equals(toID))

		if (first == false) {
			for (int i = 0; i < cdeLIST.size(); i++) {
				CDElement temp = cdeLIST.get(i);
				cdeLIST.set(i, temp);
			}
		}

		if (button.contains("download empty csv")) {
			CSVHandler csvh = new CSVHandler();
			msg = csvh.generateEmptyCSV(studytype, envtype, sessionID,
					currentlySelectedSIDs);
			mav = new ModelAndView("CSV_CREATION");
			mav.addObject("cdeLIST", cdeLIST);
			mav.addObject("origin", origin);
			mav.addObject("sSeqID", sSeqID);
			return (mav);
		}

		String second_step = (String) session.getAttribute("second_step");
		if (second_step.equals("true")) {
			String webinitial = "false";
			session.setAttribute("webinitial", webinitial);
		}
		
		final String[][] envAttributes = GetInformation.nameInformation(env);
		final String[][] studyAttributes = GetInformation.nameInformation(study);
		
		mav = new ModelAndView("3b2_CD_INPUT_ntom");
		mav.addObject("sSeqID", sSeqID);
		if (context_exists.equals("yes")) {
			List<CDElement> oldLIST = (List<CDElement>) session
					.getAttribute("oldLIST");
			mav.addObject("oldLIST", oldLIST);
		}
		mav.addObject("envAttributes", envAttributes);
		mav.addObject("studyAttributes", studyAttributes);
		mav.addObject("studyName", GetInformation.getLongNameForStudy(study));
		mav.addObject("study", studytype);
		mav.addObject("environment", envtype);
		mav.addObject("environmentName", GetInformation.getLongNameForEnvironment(env));
		return (mav);
	}
}
